import { message } from 'antd';
import { history } from 'umi';
import { request } from '@umijs/max';

// 模拟登录 API
const fakeLoginApi = (data: { username: string; password: string }) => {
  console.log(data, 'login.ts');
  return request<API.Response<string>>('/v1/system/login', { method: 'POST', data });
};

export default {
  namespace: 'login',

  state: {
    status: undefined,
    currentUser: null,
    token: '11111',

  },

  effects: {
    *login({ payload }, { call, put }) {
      const { username, password, remember } = payload;
      
      try {
        const response = yield call(fakeLoginApi, {username, password});
        console.log('111', response);

        if (response.success) {
          // 存储 token 和用户信息
          const { token, userInfo } = response.data;
          
          // 如果选择了"记住我"，则将信息存储到 localStorage
          if (remember) {
            localStorage.setItem('token', token);
            localStorage.setItem('userInfo', JSON.stringify(userInfo));
          } else {
            // 否则存储到 sessionStorage
            sessionStorage.setItem('token', token);
            sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
          }

          // 更新 state
          yield put({
            type: 'updateState',
            payload: {
              status: 'success',
              currentUser: userInfo,
              token,
            },
          });

          return { status: 'success' };
        } else {
          yield put({
            type: 'updateState',
            payload: {
              status: 'error',
            },
          });
          message.error(response.message || '登录失败');
          return { status: 'error' };
        }
      } catch (error) {
        yield put({
          type: 'updateState',
          payload: {
            status: 'error',
          },
        });
        message.error('登录过程中发生错误');
        return { status: 'error' };
      }
    },

    *logout(_, { put }) {
      // 清除存储的信息
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('userInfo');

      yield put({
        type: 'updateState',
        payload: {
          status: undefined,
          currentUser: null,
          token: null,
        },
      });

      history.push('/login');
    },
  },

  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};